<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { getClusterList } from '@/api/cluster'; // 假设你的API方法在这里
import { useClusterStore } from '@/stores/cluster';

const clusters = ref([]);
const selectedCluster = ref(null);
const showPicker = ref(false); // 控制弹窗显示状态
const fieldValue = ref(''); // 显示选择的集群名称
const router = useRouter();
const clusterStore = useClusterStore();

// 获取集群列表
const fetchClusters = async () => {
  try {
    const data = await getClusterList();
    clusters.value = data.map(cluster => ({
      id: cluster.id,
      clusterName: cluster.clusterName,
      version: cluster.version,
      url: cluster.url,
      token: cluster.token,
    }));
  } catch (error) {
    console.error('获取集群列表失败:', error);
  }
};

// 确认选择集群
const onConfirm = ({ selectedOptions }) => {
  const selected = selectedOptions[0];
  selectedCluster.value = clusters.value.find(cluster => cluster.id === selected.value);
  fieldValue.value = selected.text;
  showPicker.value = false;
  showToast(`选择了 ${selected.text}`);

  // 设置当前集群并跳转到目标页面
  if (selectedCluster.value) {
    clusterStore.setCurrentCluster(selectedCluster.value);
    router.push({ name: 'DolphinProject', params: { clusterId: selectedCluster.value.id} });
  }
};

// 监听 dophin 运维点击事件
const handleDophinOpsClick = () => {
  showPicker.value = true; // 显示弹窗
};

onMounted(fetchClusters);
</script>

<template>
  <van-grid :column-num="3">
    <!-- Dolphin 运维 -->
    <van-grid-item icon="photo-o" text="dophin运维" @click="handleDophinOpsClick" />

    <!-- 其他运维选项 -->
    <van-grid-item icon="photo-o" text="flink运维"/>
    <van-grid-item icon="photo-o" text="kafka运维" />
    <van-grid-item icon="photo-o" text="告警设置" />
    <van-grid-item icon="photo-o" text="任务状态统计" />
    <van-grid-item icon="photo-o" text="其他..." to= '/test'/>
  </van-grid>

  <!-- 弹出层选择集群 -->
  <van-popup v-model:show="showPicker" position="bottom" round destroy-on-close>
    <van-picker
      :columns="clusters.map(cluster => ({ text: cluster.clusterName, value: cluster.id }))"
      @confirm="onConfirm"
      @cancel="showPicker = false"
      title="选择集群"
    />
  </van-popup>

  <!-- 显示已选择的集群名称 -->
  <div v-if="fieldValue" class="selected-cluster">
    已选择集群：{{ fieldValue }}
  </div>
</template>

<style scoped>
/* 添加必要的样式 */
.van-field {
  margin-top: 1rem;
}
.selected-cluster {
  margin-top: 1rem;
  font-weight: bold;
}
</style>